

<template>
    <tm-app class="groupManage" bgImg="f5">
        <!-- <image
            class="psa"
            style="width:750rpx;height:834rpx;top:0;left:0;right:0;z-index:1;"
            src="../../static/bg1.jpg"
            mode=""
        ></image> -->
        <view
            style="background: #fff"
            :style="{ height: systemInfo.statusBarHeight + 'px' }"
        ></view>
        <view
            class="slim_header d-flex a-center j-center"
            style="border-bottom: none"
            :style="{ top: systemInfo.statusBarHeight + 'px' }"
        >
            <view class="left_box" @tap="goBack">
                <image src="/static/center/back.png" class="back"></image>
            </view>

            <view class="title">食物营养信息</view>
            <view class="right_box" @tap="toggleCollect">
                <i v-if="!isCollect" style="font-size:34rpx;" class="icon icon-a-aixin2"></i>
                <i v-if="isCollect" style="font-size:34rpx;color:#1dc691;" class="icon icon-aixin"></i>
                <text style="color:#999;font-weight:400;font-size:26rpx;margin-left:5rpx;">收藏</text>
                <!-- <image src="/static/center/dian.png" class="dian"></image> -->
            </view>
        </view>

        <view
            class="content"
            :style="{ top: `calc(100rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <scroll-view class="scr" :scroll-y="true">
                <view class="card">
                    <view class="title_main d-flex a-center j-between">
                        <view class="d-flex a-center">
                            <view class="vertical"></view>
                            <text class="text1" style="max-width:250rpx;">{{ food.name }}</text>
                            <text class="text2">{{ food.heat }}千卡/100g</text>
                        </view>
                        <view class="d-flex a-center">
                            <view class="dot" :class="foodLightClass"></view>
                            <view class="text3">{{foodLightText}}</view>
                        </view>
                    </view>

                    <view class="mid d-flex j-between">
                        <view class="left_box d-flex d-c a-center">
                            <view class="chartBox d-flex a-center j-center psr">
                                <tm-chart ref="chartDom" :width="190" :height="190" @onInit="chartInit"></tm-chart>
                                <view class="heat wh-center">
                                    <text class="num">{{heatNum}}</text>
                                    <text class="unit">{{heatUnit}}</text>
                                    
                                </view>
                            </view>

                            <view class="desp d-flex a-center j-center" @tap="toggleUnit"
                                >切换至{{unit==='kcal'?'千焦':'千卡'}}</view
                            >
                        </view>
                        <view class="right_box d-flex d-c">
                            <view class="title d-flex a-center">
                                <view class="c1">主要营养</view>
                                <view class="c2">含量</view>
                                <view class="c3">供能比</view>
                            </view>
                            <view class="row d-flex">
                                <view class="c1">
                                    <view class="rect1"></view>
                                    <text>碳水化合物</text>
                                </view>
                                <view class="c2">{{ food.carbWater }}克</view>
                                <view class="c3">{{
                                    calcSupply("carbWater")
                                }}</view>
                            </view>
                            <view class="row d-flex">
                                <view class="c1">
                                    <view class="rect2"></view>
                                    <text>蛋白质</text>
                                </view>
                                <view class="c2">{{ food.protein }}克</view>
                                <view class="c3">{{
                                    calcSupply("protein")
                                }}</view>
                            </view>
                            <view class="row d-flex">
                                <view class="c1">
                                    <view class="rect3"></view>
                                    <text>脂肪</text>
                                </view>
                                <view class="c2">{{ food.fat }}克</view>
                                <view class="c3">{{ calcSupply("fat") }}</view>
                            </view>
                        </view>
                    </view>

                    <view class="warn" style="margin-top: 50rpx">
                        <image
                            class="icon_warn"
                            src="/static/warn.png"
                            mode=""
                        />
                        供能比：指该营养元素在这种食物中提供的热量占比
                    </view>

                    <view class="warn" style="margin-top: 16rpx">
                        <image
                            class="icon_warn"
                            src="/static/warn.png"
                            mode=""
                        />
                        NRV%：指100克该食物提供的营养元素占一个成年人一天所需的该营养总量的百分比
                    </view>
                </view>

                <view class="card d-flex a-center psr" style="margin-top:20rpx;">
                    <view class="box d-flex d-c a-center j-center">
                        <view class="text1 d-flex a-center">{{GI}}
                            <view class="tag d-flex a-center j-center" :class="[GIClass]">
                                {{GITagText}}
                            </view>
                        </view>
                        <view><text class="text2">升糖指数</text> <text class="text3">(GI)</text> </view>
                    </view>
                    <view class="box d-flex d-c a-center j-center">
                        <view class="text1 d-flex a-center">{{GL}}
                            <view class="tag d-flex a-center j-center" :class="[GLClass]">
                                {{GLTagText}}
                            </view>
                        </view>
                        <view><text class="text2">血糖负荷</text> <text class="text3">(GL)</text> </view>
                    </view>
                    <view class="line wh-center"></view>
                    
                </view>

                <view class="card chemical" style="margin-top: 20rpx">
                    <view class="title d-flex a-center">
                        <view class="c1">营养元素</view>
                        <view class="c2">含量(每100克)</view>
                        <view class="c3">

                            <view
                                class="d-flex a-center j-center"
                                style="width: 120rpx;"
                            >
                                NRV%
                            </view>
                            
                        </view>
                    </view>
                    <view
                        class="row d-flex a-center"
                        v-for="key in Object.keys(EN_ZH)"
                    >
                        <view class="c1">{{ EN_ZH[key] }}</view>
                        <view class="c2">{{ Number(food[key]) || "-" }}</view>
                        <view class="c3">
                            <view
                                class="d-flex a-center j-center"
                                style="width: 120rpx;"
                            >
                                {{ calcNVR(key) }}
                            </view>
                        </view>
                    </view>
                </view>

                <view class="heightBox"></view>
            </scroll-view>

            <!-- <Echart :option="option" :width="width" :height="height"/> -->
        </view>
    </tm-app>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { onReady, onShow, onLoad, onUnload } from "@dcloudio/uni-app";
import { userData as userDataStore } from "@/store/userData";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { imStore } from "@/store/imStore";
import { config as configStore } from "@/store/config";
import { getFoodDetail,getUserHealth,editFoodCollect,foodIsCollect } from "@/api/api";
const IM_STORE = imStore();
const userData: any = userDataStore();
const isCollect = ref(false);
// const width = ref(170)
// const height = ref(170)

const toggleCollect = async ()=>{
    let optType = isCollect.value?0:1

    let params = {
		userId:userData.id,
		code:foodCode.value,
		optType:optType,
	}

    await editFoodCollect(params);

    isCollect.value = !isCollect.value;
}

// const aaa = ()=>{
//     option.value.series[0].data[0].value = 3000;
// }
const food = ref({});

const EN_ZH = ref({
    //carbWater: "碳水化合物",
    //fat: "脂肪",
    //protein: "蛋白质",
    cellulose: "膳食纤维（克）",
    va: "维生素A（微克）",
    pyridoxine:"维生素B6（毫克）",
    cobalamin:'维生素B12（微克）',
    vc: "维生素C（毫克）",
    vd:'维生素D（微克）',
    ve: "维生素E（毫克）",
    vk:"维生素K（微克）",
    carotene: "胡萝卜素（微克）",
    oryzanin: "维生素B1（毫克）",
    lactochrome: "维生素B2（毫克）",
    niacin: "烟酸（毫克）",
    pantothenic:"泛酸（毫克）",
    choline:"胆碱（毫克）",
    biotin:"生物素（微克）",
    cholesterol: "胆固醇（毫克）",
    magnesium: "镁（毫克）",
    calcium: "钙（毫克）",
    iron: "铁（毫克）",
    zinc: "锌（毫克）",
    copper: "铜（毫克）",
    iodine:"碘（微克）",
    manganese: "锰（毫克）",
    potassium: "钾（毫克）",
    phosphorus: "磷（毫克）",
    sodium: "钠（毫克）",
    selenium: "硒（微克）",
    chlorine:"氯（毫克）",
    // fluorine:"氟",
    // hg:"汞(ppm)",
});
const NRV_BASE = ref({
    carbWater: 300,
    fat: 60,
    protein: 60,
    cellulose: 25,
    va: 800,
    pyridoxine:1.4,
    cobalamin:25,
    vc: 100,
    vd:5,
    ve: 14,
    vk:120,
    carotene: 5000,
    oryzanin: 1.4,
    lactochrome: 1.4,
    niacin: 14,
    pantothenic:5,
    choline:450,
    biotin:30,
    cholesterol: 300,
    magnesium: 300,
    calcium: 800,
    iron: 15,
    zinc: 15,
    copper: 1.5,
    iodine:150,
    manganese: 3,
    potassium: 2000,
    phosphorus: 700,
    sodium: 2200,
    selenium: 50,
    chlorine:2300,
    // fluorine:"氟",
    // hg:"汞(ppm)",
});

const calcNVR = computed(() => (key: string) => {
    if (!food.value[key]||!Number(food.value[key])) {
        return "-";
    }
    const a = Number(food.value[key]);
    const b = Number(NRV_BASE.value[key]);
    let percent = a / b;

    let nrv = (percent * 100).toFixed(2);

    if(nrv<1){
        return '<1%'
    }else{
        return nrv+"%";
    }

});

const calcSupply = (key: string,returnNum?:boolean)=>{
    if (!food.value[key]||!Number(food.value[key])) {
        return "-";
    }
    let a = Number(food.value[key]);
    const b = Number(food.value.heat);
    if (key === "carbWater" || key === "protein") {
        a = a * 4;
    }
    if (key === "fat") {
        a = a * 9;
    }
    let percent = a / b;

    if(returnNum){
        return Math.floor(percent.toFixed(2) * 100);
    }
    return Math.floor(percent.toFixed(2) * 100) + "%";
}

const unit = ref('kcal');

const heatNum = computed(()=>{
    if(!food.value.heat){
        return '-'
    }

    if(unit.value==='kcal'){
        return food.value.heat
    }else{
        return Math.floor(Number(food.value.heat)*4.18585)
    }
})

const heatUnit = computed(()=>{
    if(!food.value.heat){
        return ''
    }

    if(unit.value==='kcal'){
        return '千卡'
    }else{
        return '千焦'
    }
})

const foodLightText = computed(()=>{
    let num = Number(food.value.healthLight);
    if(num===1){
        return '推荐食用'
    }

    if(num===2){
        return '适量食用'
    }
    if(num===3){
        return '建议少吃'
    }
})
const foodLightClass = computed(()=>{
    let num = Number(food.value.healthLight);
    return 'light'+num;
})


const GI = computed(()=>{
    if(food.value.gi){
        const [num,levelStr] = food.value.gi.split(',');
        return num||'-'
    }


    return '-';
})
const GIClass = computed(()=>{

    if(food.value.gi){
        const [num,levelStr] = food.value.gi.split(',');
        if(levelStr.startsWith('低')||levelStr.startsWith('中')){
            return 'low'
        }
        if(levelStr.startsWith('高')||levelStr.startsWith('中')){
            return 'high'
        }
    }
    return 'none';
})

const GITagText = computed(()=>{
    if(food.value.gi){
        const [num,levelStr] = food.value.gi.split(',');
        if(levelStr){
            return levelStr
        }
    }
    return '-';
})


const GL = computed(()=>{
    if(food.value.gl){
        const [num,levelStr] = food.value.gl.split(',');
        return num||'-'
    }


    return '-';
})

const GLClass = computed(()=>{
    if(food.value.gl){
        const [num,levelStr] = food.value.gl.split(',');

        console.log('GLClass')
        console.log('GLClass')
        console.log(levelStr)

        if(levelStr.startsWith('低')||levelStr.startsWith('中')){
            return 'low'
        }
        if(levelStr.startsWith('高')||levelStr.startsWith('中')){
            return 'high'
        }
    }
    return 'none';
})


const GLTagText = computed(()=>{
    if(food.value.gl){
        const [num,levelStr] = food.value.gl.split(',');
        if(levelStr){
            return levelStr
        }
    }
    return '-';
})

const toggleUnit = ()=>{
    unit.value = unit.value==='kcal'?'kj':'kcal';
}

// const calcNVR = (key:string)=>{
//     const a = Number(food.value[key]);
//     const b = Number(NRV_BASE.value[key])
//     console.log('11123123');
//     console.log(key);
//     console.log(food.value);
//     console.log(b);
//     let percent = a/b;

//     return percent.toFixed(2)

// }

const foodCode = ref(null);

const option = ref({
    series: [
        {
            name: "Access From",
            type: "pie",
            radius: ["66%", "90%"],
            avoidLabelOverlap: false,
            startAngle: 300,
            emphasis: {
                disabled: true,
            },
            // emphasis: {
            //     label: {
            //         show: true,
            //         fontSize: 40,
            //         fontWeight: "bold",
            //     },
            // },
            labelLine: {
                show: false,
            },
            data: [

                {
                    value: 200,
                    name: "",
                    itemStyle: {
                        color: {
                            type: "linear",
                            x: 0,
                            y: 0.1,
                            x2: 1,
                            y2: 0.1,
                            colorStops: [
                                {
                                    offset: 0,
                                    color: "#F5F5F5", // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: "#F5F5F5", // 0% 处的颜色
                                },
                            ],
                        },
                        shadowColor: "rgba(0, 0, 0, 0.1)",
                        shadowBlur: 0,
                        borderColor: "#ffffff",
                        borderWidth: 1,
                    },
                },

                {
                    value: 1000,
                    name: "",
                    itemStyle: {
                        color: {
                            type: "linear",
                            x: 0,
                            y: 0.1,
                            x2: 1,
                            y2: 0.1,
                            colorStops: [
                                {
                                    offset: 0,
                                    color: "#FF7B5F", // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: "#FF5932", // 0% 处的颜色
                                },
                            ],
                        },
                        shadowColor: "rgba(0, 0, 0, 0.1)",
                        shadowBlur: 7,
                        borderRadius: "50%",
                        borderColor: "#ffffff",
                        borderWidth: 1,
                    },
                },

                {
                    value: 1048,
                    name: "",
                    itemStyle: {
                        color: {
                            type: "linear",
                            x: 0,
                            y: 0.1,
                            x2: 1,
                            y2: 0.1,
                            colorStops: [
                                {
                                    offset: 0,
                                    color: "#3EE4C3", // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: "#1DC691", // 0% 处的颜色
                                },
                            ],
                        },
                        shadowColor: "rgba(0, 0, 0, 0.1)",
                        shadowBlur: 7,
                        borderRadius: "50%",
                        borderColor: "#ffffff",
                        borderWidth: 1,
                    },
                },

                {
                    value: 1000,
                    name: "",
                    itemStyle: {
                        color: {
                            type: "linear",
                            x: 0,
                            y: 0.1,
                            x2: 1,
                            y2: 0.1,
                            colorStops: [
                                {
                                    offset: 0,
                                    color: "#FFC577", // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: "#FFAF67", // 0% 处的颜色
                                },
                            ],
                        },
                        shadowColor: "rgba(0, 0, 0, 0.1)",
                        shadowBlur: 7,
                        borderRadius: "50%",
                        borderColor: "#ffffff",
                        borderWidth: 1,
                    },
                },
                
                
            ],
        },
    ],
});

let mychart = null;

 const chartInit=(chart: ECharts)=>{
	mychart = chart;
}

const setOption = ()=>{
    if(mychart){
        mychart.setOption(option.value);
    }else{
        setTimeout(()=>{
            setOption();
        },100)
    }
}

const GetFoodDetail = async (code) => {
    if (!code) {
        return;
    }
    const params = {
        code,
    };
    const res = await getFoodDetail(params);
    const { flag, data } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "获取食物详情失败",
            duration: 1500,
        });
        return;
    }

    food.value = data;


    const data1 = calcSupply('fat',true)
    const data2 = calcSupply('carbWater',true)
    const data3 = calcSupply('protein',true)


    const total = data1+data2+data3;

    let data0 = 100 - total;
    

    

    option.value.series[0].data[0].value=data0;
    option.value.series[0].data[1].value=data1;
    option.value.series[0].data[2].value=data2;
    option.value.series[0].data[3].value=data3;


    setOption();
};

const getIsCollect = async (code) => {
    const params = {
        userId:userData.id,
        code
    }
    const res = await foodIsCollect(params)
    const {flag,data} = res;
    isCollect.value = data.data;
}

const systemInfo: any = systemInfoStore();

const goBack = () => {
    uni.navigateBack();
};

const goJoinList = () => {
    uni.navigateTo({
        url: `/pages/TUIKit/TUIPages/TUIGroup/groupPages/groupJoinList?groupId=${groupId.value}`,
    });
};

const searched = ref(false);

const searchText = ref("");

const GetUserHealth = async()=>{
    const {flag,data} = await getUserHealth({userId:userData.id})

    if(data)


    console.log(res);
}

onReady(() => {});

onLoad((option: any) => {
    if (option.code) {
        foodCode.value = option.code;
        GetFoodDetail(foodCode.value);
        getIsCollect(foodCode.value);
        GetUserHealth();
    }
});

onUnload(() => {});

onShow(() => {});
</script>

<style lang="scss" scoped>
.groupManage {
    .content {
        position: absolute;
        width: 750rpx;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        flex-direction: column;
        padding-top: 20rpx;

        .scr {
            position: absolute;
            top: 20rpx;
            bottom: 0;
            .heightBox {
                height: constant(safe-area-inset-bottom);
                height: env(safe-area-inset-bottom);
                min-height: 20rpx;
            }
        }

        .card {
            width: 710rpx;
            padding: 30rpx;
            background: #fff;
            border-radius: 20rpx;
            margin: 0 auto;
            .line{
                width: 2rpx;
                height: 80rpx;
                background: #F5F5F5;
                border-radius: 1rpx;
            }
            .box{
                width:50%;
                height:140rpx;
                .text1{
                    font-size: 32rpx;
                    font-weight: 600;
                    color: #333333;
                    height:50rpx;
                }
                .text2{
                    font-size: 26rpx;
                    font-weight: 400;
                    color: #333333;
                }
                .text3{
                    font-size: 26rpx;
                    font-weight: 400;
                    color: #999;
                }

                .tag{
                    width: 60rpx;
                    height: 32rpx;
                    border-radius: 4rpx;
                    font-size: 20rpx;
                    font-weight: 400;
                    margin-left:10rpx;
                    &.low{
                        color: #1DC691;
                        background:#D2F4E9;
                    }
                    &.high{
                        color: #E8612E;
                        background:#FFE3D9;
                    }
                    &.none{
                        display:none;
                    }
                }
            }
        }

        .title_main {
            padding-right: 8rpx;
            .vertical {
                width: 6rpx;
                height: 30rpx;
                background: #1dc691;
                border-radius: 3rpx;
                margin-right: 16rpx;
            }

            .text1 {
                font-size: 32rpx;
                color: #333;
                font-weight: 600;
                margin-right: 10rpx;
            }

            .text2 {
                font-size: 24rpx;
                color: #999;
            }
            .text3 {
                font-size: 28rpx;
                color: #666;
            }

            .dot {
                width: 30rpx;
                height: 30rpx;
                border-radius: 15rpx;
                margin-right: 10rpx;
                &.light1{
                    background: #1dc691;
                }
                &.light2{
                    background: #FFC578;
                }
                &.light3{
                    background: #FF7B5F;
                }
            }
        }

        .mid {
            width: 100%;
            height: 230rpx;
            margin-top: 30rpx;
            .left_box {
                width: 190rpx;
                height: 100%;
                justify-content: space-between;
                .chartBox {
                    width: 190rpx;
                    height: 190rpx;
                    .heat{
                        white-space: nowrap;
                        .num{
                            font-size:32rpx;
                            font-family: "din",DINAlternate-Bold, DINAlternate;
                            font-weight:bold;
                            white-space: nowrap;
                        }
                        .unit{
                            font-size:20rpx;
                            white-space: nowrap;
                        }

                    }
                }
                .desp {
                    width: 120rpx;
                    height: 36rpx;
                    background: #f5f5f5;
                    border-radius: 18rpx;
                    font-size: 20rpx;
                    color: #999;
                }
            }

            .right_box {
                width: 440rpx;
                height: 230rpx;
                background: rgba(29, 198, 145, 0.07);
                border-radius: 20px;
                padding: 15rpx 0;
                padding-left: 20rpx;
                .c1 {
                    width: 160rpx;
                    display: flex;
                    align-items: center;
                }
                .c2 {
                    width: 150rpx;
                    text-align: center;
                }
                .c3 {
                    flex: 1;
                    text-align: center;
                }
                .title {
                    width: 100%;
                    height: 50rpx;
                    font-size: 24rpx;
                    color: #999;
                    line-height: 50rpx;
                    .c1 {
                        justify-content: center;
                    }
                }
                .row {
                    width: 100%;
                    height: 50rpx;
                    font-size: 24rpx;
                    color: #333;
                    line-height: 50rpx;
                }
                .rect1 {
                    width: 20rpx;
                    height: 20rpx;
                    background: linear-gradient(
                        90deg,
                        #3ee5c4 0%,
                        #1dc691 100%
                    );
                    border-radius: 5rpx;
                    margin-right: 10rpx;
                }
                .rect2 {
                    width: 20rpx;
                    height: 20rpx;
                    background: linear-gradient(
                        90deg,
                        #ffc578 0%,
                        #ffaf67 100%
                    );
                    border-radius: 5rpx;
                    margin-right: 10rpx;
                }
                .rect3 {
                    width: 20rpx;
                    height: 20rpx;
                    background: linear-gradient(
                        90deg,
                        #ff7b5f 0%,
                        #ff5831 100%
                    );
                    border-radius: 5rpx;
                    margin-right: 10rpx;
                }
            }
        }

        .warn {
            position: relative;
            padding-left: 50rpx;
            color: #eaa04f;
            font-size: 24rpx;
            line-height: 33rpx;
            .icon_warn {
                position: absolute;
                left: 0;
                width: 32rpx;
                height: 32rpx;
            }
        }

        .chemical {
            .title {
                width: 100%;
                height: 50rpx;
                font-size: 24rpx;
                color: #999;
            }

            .row {
                width: 100%;
                height: 50rpx;
                font-size: 24rpx;
                color: #333;
            }

            .c1 {
                width: 35%;
            }
            .c2 {
                width: 33.33%;
                text-align: center;
            }
            .c3 {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: end;
            }
        }
    }
}
</style>
